import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 配置 NProgress
NProgress.configure({ 
  showSpinner: false,
  minimum: 0.2,
  easing: 'ease',
  speed: 500
})

// 菜单分类配置
export const menuCategories = [
  {
    id: 'dashboard',
    title: '仪表盘',
    icon: 'Monitor',
    color: '#409eff',
    description: '系统概览和数据统计'
  },
  {
    id: 'system',
    title: '系统管理',
    icon: 'Setting',
    color: '#67c23a',
    description: '用户、角色、权限、租户管理'
  },
  {
    id: 'education',
    title: '教育服务',
    icon: 'School',
    color: '#e6a23c',
    description: '课堂、考试、任务管理'
  },
  {
    id: 'development',
    title: '开发工具',
    icon: 'Notebook',
    color: '#f56c6c',
    description: '编程、版本控制'
  },
  {
    id: 'content',
    title: '内容管理',
    icon: 'Document',
    color: '#909399',
    description: '新闻、文章、图书管理'
  },
  {
    id: 'business',
    title: '业务管理',
    icon: 'ShoppingCart',
    color: '#722ed1',
    description: '商城、支付、订单管理'
  },
  {
    id: 'communication',
    title: '沟通交流',
    icon: 'ChatDotRound',
    color: '#13c2c2',
    description: '聊天、AI对话管理'
  },
  {
    id: 'storage',
    title: '存储管理',
    icon: 'Folder',
    color: '#52c41a',
    description: '文档、网盘、文件管理'
  }
]

// 路由配置
export const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login/index.vue'),
    meta: {
      title: '登录',
      hidden: true
    }
  },
  {
    path: '/',
    component: () => import('@/layouts/index.vue'),
    redirect: '/dashboard',
    meta: {
      category: 'dashboard'
    },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard/index.vue'),
        meta: {
          title: '仪表盘',
          icon: 'DataAnalysis',
          affix: true,
          category: 'dashboard'
        }
      }
    ]
  },
  {
    path: '/system',
    component: () => import('@/layouts/index.vue'),
    meta: {
      title: '系统管理',
      icon: 'Setting',
      category: 'system'
    },
    children: [
      {
        path: 'user',
        name: 'UserManagement',
        component: () => import('@/views/System/User/index.vue'),
        meta: {
          title: '用户管理',
          icon: 'User',
          category: 'system'
        }
      },
      {
        path: 'user/create',
        name: 'UserCreate',
        component: () => import('@/views/User/User/form.vue'),
        meta: {
          title: '新增用户',
          hidden: true,
          activeMenu: '/system/user'
        }
      },
      {
        path: 'user/edit/:id',
        name: 'UserEdit',
        component: () => import('@/views/User/User/form.vue'),
        meta: {
          title: '编辑用户',
          hidden: true,
          activeMenu: '/system/user'
        }
      },
      {
        path: 'user/detail/:id',
        name: 'UserDetail',
        component: () => import('@/views/User/User/detail.vue'),
        meta: {
          title: '用户详情',
          hidden: true,
          activeMenu: '/system/user'
        }
      },
      {
        path: 'role',
        name: 'RoleManagement',
        component: () => import('@/views/System/Role/index.vue'),
        meta: {
          title: '角色管理',
          icon: 'UserFilled',
          category: 'system'
        }
      },
      {
        path: 'role/create',
        name: 'RoleCreate',
        component: () => import('@/views/User/Role/form.vue'),
        meta: {
          title: '新增角色',
          hidden: true,
          activeMenu: '/system/role'
        }
      },
      {
        path: 'role/edit/:id',
        name: 'RoleEdit',
        component: () => import('@/views/User/Role/form.vue'),
        meta: {
          title: '编辑角色',
          hidden: true,
          activeMenu: '/system/role'
        }
      },
      {
        path: 'permission',
        name: 'PermissionManagement',
        component: () => import('@/views/System/Permission/index.vue'),
        meta: {
          title: '权限管理',
          icon: 'Lock',
          category: 'system'
        }
      },
      {
        path: 'tenant',
        name: 'TenantManagement',
        component: () => import('@/views/System/Tenant/index.vue'),
        meta: {
          title: '租户管理',
          icon: 'OfficeBuilding',
          category: 'system',
          roles: ['SUPER_ADMIN'] // 只有超级管理员可以访问
        }
      },
      {
        path: 'tenant/create',
        name: 'TenantCreate',
        component: () => import('@/views/System/Tenant/index.vue'),
        meta: {
          title: '新增租户',
          hidden: true,
          activeMenu: '/system/tenant',
          roles: ['SUPER_ADMIN']
        }
      },
      {
        path: 'tenant/edit/:id',
        name: 'TenantEdit',
        component: () => import('@/views/System/Tenant/index.vue'),
        meta: {
          title: '编辑租户',
          hidden: true,
          activeMenu: '/system/tenant',
          roles: ['SUPER_ADMIN']
        }
      },
      {
        path: 'tenant/detail/:id',
        name: 'TenantDetail',
        component: () => import('@/views/System/Tenant/index.vue'),
        meta: {
          title: '租户详情',
          hidden: true,
          activeMenu: '/system/tenant',
          roles: ['SUPER_ADMIN']
        }
      }
    ]
  },
  {
    path: '/classroom',
    component: () => import('@/layouts/index.vue'),
    meta: {
      title: '智能课堂',
      icon: 'School',
      category: 'education'
    },
    children: [
      {
        path: 'course',
        name: 'CourseManagement',
        component: () => import('@/views/Classroom/Course/index.vue'),
        meta: {
          title: '课程管理',
          icon: 'Reading'
        }
      },
      {
        path: 'course/create',
        name: 'CourseCreate',
        component: () => import('@/views/Classroom/Course/form.vue'),
        meta: {
          title: '新增课程',
          hidden: true,
          activeMenu: '/classroom/course'
        }
      },
      {
        path: 'course/edit/:id',
        name: 'CourseEdit',
        component: () => import('@/views/Classroom/Course/form.vue'),
        meta: {
          title: '编辑课程',
          hidden: true,
          activeMenu: '/classroom/course'
        }
      },
      {
        path: 'course/detail/:id',
        name: 'CourseDetail',
        component: () => import('@/views/Classroom/CourseDetail.vue'),
        meta: {
          title: '课程详情',
          hidden: true,
          activeMenu: '/classroom/course'
        }
      },
      {
        path: 'chapter',
        name: 'ChapterManagement',
        component: () => import('@/views/Classroom/Chapter/index.vue'),
        meta: {
          title: '章节管理',
          icon: 'Document'
        }
      },
      {
        path: 'lesson',
        name: 'LessonManagement',
        component: () => import('@/views/Classroom/Lesson/index.vue'),
        meta: {
          title: '课时管理',
          icon: 'VideoPlay'
        }
      }
    ]
  },
  {
    path: '/exam',
    component: () => import('@/layouts/index.vue'),
    meta: {
      title: '考试管理',
      icon: 'Edit',
      category: 'education'
    },
    children: [
      {
        path: 'exam',
        name: 'ExamManagement',
        component: () => import('@/views/Exam/Exam/index.vue'),
        meta: {
          title: '考试管理',
          icon: 'EditPen'
        }
      },
      {
        path: 'exam/create',
        name: 'ExamCreate',
        component: () => import('@/views/Exam/Exam/form.vue'),
        meta: {
          title: '新增考试',
          hidden: true,
          activeMenu: '/exam/exam'
        }
      },
      {
        path: 'exam/edit/:id',
        name: 'ExamEdit',
        component: () => import('@/views/Exam/Exam/form.vue'),
        meta: {
          title: '编辑考试',
          hidden: true,
          activeMenu: '/exam/exam'
        }
      },
      {
        path: 'exam/detail/:id',
        name: 'ExamDetail',
        component: () => import('@/views/Exam/Exam/detail.vue'),
        meta: {
          title: '考试详情',
          hidden: true,
          activeMenu: '/exam/exam'
        }
      },
      {
        path: 'question',
        name: 'QuestionManagement',
        component: () => import('@/views/Exam/Question/index.vue'),
        meta: {
          title: '题目管理',
          icon: 'QuestionFilled'
        }
      },
      {
        path: 'record',
        name: 'ExamRecordManagement',
        component: () => import('@/views/Exam/Record/index.vue'),
        meta: {
          title: '考试记录',
          icon: 'Tickets'
        }
      }
    ]
  },
  {
    path: '/coding',
    component: () => import('@/layouts/index.vue'),
    meta: {
      title: '编程实战',
      icon: 'Monitor',
      category: 'development'
    },
    children: [
      {
        path: 'problem',
        name: 'ProblemManagement',
        component: () => import('@/views/Coding/Problem/index.vue'),
        meta: {
          title: '题目管理',
          icon: 'Cpu'
        }
      },
      {
        path: 'submission',
        name: 'SubmissionManagement',
        component: () => import('@/views/Coding/Submission/index.vue'),
        meta: {
          title: '提交记录',
          icon: 'List'
        }
      }
    ]
  },
  {
    path: '/task',
    component: () => import('@/layouts/index.vue'),
    meta: {
      title: '任务管理',
      icon: 'Checked',
      category: 'education'
    },
    children: [
      {
        path: 'task',
        name: 'TaskManagement',
        component: () => import('@/views/Task/Task/index.vue'),
        meta: {
          title: '任务管理',
          icon: 'List',
          category: 'education'
        }
      },
      {
        path: 'template',
        name: 'TaskTemplateManagement',
        component: () => import('@/views/Task/Template/index.vue'),
        meta: {
          title: '任务模板',
          icon: 'Document',
          category: 'education'
        }
      }
    ]
  },
  {
    path: '/news',
    component: () => import('@/layouts/index.vue'),
    meta: {
      title: '资讯管理',
      icon: 'Notification',
      category: 'content'
    },
    children: [
      {
        path: 'news',
        name: 'NewsManagement',
        component: () => import('@/views/News/News/index.vue'),
        meta: {
          title: '新闻管理',
          icon: 'ChatDotRound',
          category: 'content'
        }
      },
      {
        path: 'news/detail/:id',
        name: 'NewsDetail',
        component: () => import('@/views/News/NewsDetail.vue'),
        meta: {
          title: '新闻详情',
          hidden: true,
          activeMenu: '/news/news',
          category: 'content'
        }
      },
      {
        path: 'category',
        name: 'NewsCategoryManagement',
        component: () => import('@/views/News/Category/index.vue'),
        meta: {
          title: '新闻分类',
          icon: 'Menu',
          category: 'content'
        }
      }
    ]
  },
  {
    path: '/library',
    component: () => import('@/layouts/index.vue'),
    meta: {
      title: '图书管理',
      icon: 'Reading',
      category: 'content'
    },
    children: [
      {
        path: 'book',
        name: 'BookManagement',
        component: () => import('@/views/Library/Book/index.vue'),
        meta: {
          title: '图书管理',
          icon: 'Notebook'
        }
      },
      {
        path: 'borrow',
        name: 'BorrowManagement',
        component: () => import('@/views/Library/Borrow/index.vue'),
        meta: {
          title: '借阅管理',
          icon: 'DocumentCopy'
        }
      },
      {
        path: 'category',
        name: 'LibraryCategoryManagement',
        component: () => import('@/views/Library/Category/index.vue'),
        meta: {
          title: '图书分类',
          icon: 'Menu'
        }
      }
    ]
  },
  {
    path: '/mall',
    component: () => import('@/layouts/index.vue'),
    meta: {
      title: '商城管理',
      icon: 'ShoppingCart',
      category: 'business'
    },
    children: [
      {
        path: 'product',
        name: 'ProductManagement',
        component: () => import('@/views/Mall/Product/index.vue'),
        meta: {
          title: '商品管理',
          icon: 'Goods'
        }
      },
      {
        path: 'order',
        name: 'OrderManagement',
        component: () => import('@/views/Mall/Order/index.vue'),
        meta: {
          title: '订单管理',
          icon: 'List'
        }
      },
      {
        path: 'payment',
        name: 'PaymentManagement',
        component: () => import('@/views/Mall/Payment/index.vue'),
        meta: {
          title: '支付管理',
          icon: 'Money'
        }
      }
    ]
  },
  {
    path: '/chat',
    component: () => import('@/layouts/index.vue'),
    meta: {
      title: '聊天管理',
      icon: 'ChatDotRound',
      category: 'communication'
    },
    children: [
      {
        path: 'room',
        name: 'ChatRoomManagement',
        component: () => import('@/views/Chat/Room/index.vue'),
        meta: {
          title: '聊天室管理',
          icon: 'ChatRound',
          category: 'communication'
        }
      },
      {
        path: 'message',
        name: 'MessageManagement',
        component: () => import('@/views/Chat/Message/index.vue'),
        meta: {
          title: '消息管理',
          icon: 'Message',
          category: 'communication'
        }
      },
      {
        path: 'chatroom-users',
        name: 'ChatUserManagement',
        component: () => import('@/views/Chat/User/index.vue'),
        meta: {
          title: '聊天用户',
          icon: 'User',
          category: 'communication'
        }
      }
    ]
  },
  {
    path: '/ai-chat',
    component: () => import('@/layouts/index.vue'),
    meta: {
      title: 'AI聊天管理',
      icon: 'Cpu',
      category: 'communication'
    },
    children: [
      {
        path: 'model',
        name: 'AiModelManagement',
        component: () => import('@/views/AiChat/Model/index.vue'),
        meta: {
          title: 'AI模型管理',
          icon: 'Setting',
          category: 'communication'
        }
      },
      {
        path: 'chat',
        name: 'AiChatManagement',
        component: () => import('@/views/AiChat/Chat/index.vue'),
        meta: {
          title: '聊天记录',
          icon: 'ChatDotRound',
          category: 'communication'
        }
      },
      {
        path: 'config',
        name: 'AiConfigManagement',
        component: () => import('@/views/AiChat/Config/index.vue'),
        meta: {
          title: 'AI配置',
          icon: 'Tools',
          category: 'communication'
        }
      }
    ]
  },
  {
    path: '/article',
    component: () => import('@/layouts/index.vue'),
    meta: {
      title: '文章管理',
      icon: 'Document',
      category: 'content'
    },
    children: [
      {
        path: 'article',
        name: 'ArticleManagement',
        component: () => import('@/views/Article/Article/index.vue'),
        meta: {
          title: '文章管理',
          icon: 'Document',
          category: 'content'
        }
      },
      {
        path: 'category',
        name: 'ArticleCategoryManagement',
        component: () => import('@/views/Article/Category/index.vue'),
        meta: {
          title: '文章分类',
          icon: 'Menu',
          category: 'content'
        }
      },
      {
        path: 'tag',
        name: 'TagManagement',
        component: () => import('@/views/Article/Tag/index.vue'),
        meta: {
          title: '标签管理',
          icon: 'PriceTag',
          category: 'content'
        }
      }
    ]
  },
  {
    path: '/note',
    component: () => import('@/layouts/index.vue'),
    meta: {
      title: '笔记管理',
      icon: 'Notebook',
      category: 'content'
    },
    children: [
      {
        path: 'note',
        name: 'NoteManagement',
        component: () => import('@/views/Note/Note/index.vue'),
        meta: {
          title: '笔记管理',
          icon: 'Notebook',
          category: 'content'
        }
      },
      {
        path: 'category',
        name: 'NoteCategoryManagement',
        component: () => import('@/views/Note/Category/index.vue'),
        meta: {
          title: '笔记分类',
          icon: 'Menu',
          category: 'content'
        }
      }
    ]
  },
  {
    path: '/document',
    component: () => import('@/layouts/index.vue'),
    meta: {
      title: '文档管理',
      icon: 'FolderOpened',
      category: 'storage'
    },
    children: [
      {
        path: 'document',
        name: 'DocumentManagement',
        component: () => import('@/views/Document/Document/index.vue'),
        meta: {
          title: '文档管理',
          icon: 'Document',
          category: 'storage'
        }
      },
      {
        path: 'doc-template',
        name: 'DocumentTemplateManagement',
        component: () => import('@/views/Document/Template/index.vue'),
        meta: {
          title: '文档模板',
          icon: 'DocumentCopy',
          category: 'storage'
        }
      }
    ]
  },
  {
    path: '/disk',
    component: () => import('@/layouts/index.vue'),
    meta: {
      title: '网盘管理',
      icon: 'Folder',
      category: 'storage'
    },
    children: [
      {
        path: 'file',
        name: 'FileManagement',
        component: () => import('@/views/Disk/File/index.vue'),
        meta: {
          title: '文件管理',
          icon: 'Document',
          category: 'storage'
        }
      },
      {
        path: 'folder',
        name: 'FolderManagement',
        component: () => import('@/views/Disk/Folder/index.vue'),
        meta: {
          title: '文件夹管理',
          icon: 'Folder',
          category: 'storage'
        }
      },
      {
        path: 'share',
        name: 'ShareManagement',
        component: () => import('@/views/Disk/Share/index.vue'),
        meta: {
          title: '分享管理',
          icon: 'Share',
          category: 'storage'
        }
      }
    ]
  },
  {
    path: '/version',
    component: () => import('@/layouts/index.vue'),
    meta: {
      title: '版本控制',
      icon: 'Operation',
      category: 'development'
    },
    children: [
      {
        path: 'repository',
        name: 'RepositoryManagement',
        component: () => import('@/views/Version/Repository/index.vue'),
        meta: {
          title: '仓库管理',
          icon: 'Box',
          category: 'development'
        }
      },
      {
        path: 'branch',
        name: 'BranchManagement',
        component: () => import('@/views/Version/Branch/index.vue'),
        meta: {
          title: '分支管理',
          icon: 'Share',
          category: 'development'
        }
      },
      {
        path: 'commit',
        name: 'CommitManagement',
        component: () => import('@/views/Version/Commit/index.vue'),
        meta: {
          title: '提交记录',
          icon: 'List',
          category: 'development'
        }
      }
    ]
  },
  {
    path: '/403',
    name: 'Forbidden',
    component: () => import('@/views/Error/403.vue'),
    meta: {
      title: '访问被拒绝',
      hidden: true
    }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/Error/404.vue'),
    meta: {
      title: '页面未找到',
      hidden: true
    }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory('/'),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  NProgress.start()

  const userStore = useUserStore()

  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - ZenithMind后台管理系统`
  }

  // 白名单路由
  const whiteList = ['/login']

  // 调试信息
  console.log('路由守卫: ', {
    path: to.path,
    fullPath: to.fullPath,
    token: !!userStore.token,
    userInfo: !!userStore.userInfo
  })

  // 如果是白名单路由，直接通过
  if (whiteList.includes(to.path)) {
    next()
    return
  }

  // 如果有token
  if (userStore.token) {
    // 如果已登录用户访问登录页，重定向到首页
    if (to.path === '/login') {
      next('/dashboard')
      return
    }

    // 检查是否有用户信息
    if (!userStore.userInfo) {
      try {
        await userStore.getUserInfo()
      } catch (error) {
        console.error('获取用户信息失败:', error)
        userStore.logout()
        next('/login')
        return
      }
    }

    // 检查路由权限
    if (to.meta && to.meta.roles) {
      const hasRole = to.meta.roles.some(role => userStore.hasRole(role))
      if (!hasRole) {
        // 没有权限，重定向到403页面或首页
        next('/403')
        return
      }
    }

    next()
  } else {
    // 没有token，重定向到登录页
    next('/login')
  }
})

// 全局后置守卫
router.afterEach((to) => {
  NProgress.done()

  const appStore = useAppStore()

  // 添加访问的视图
  if (to.meta && to.meta.title) {
    appStore.addVisitedView(to)
    appStore.addCachedView(to)
  }
})

export default router
